package com.kedacom.freedomLabel.view.fragment.setting;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;

import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.AppConfig;
import com.kedacom.freedomLabel.databinding.FragmentCorrectionSettingBinding;
import com.kedacom.freedomLabel.utils.NumFormatUtil;
import com.kedacom.freedomLabel.view.activity.ScaleActivity;
import com.kedacom.freedomLabel.viewmodel.CorrectionSettingViewModel;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.util.Utils;
import com.lzscale.scalelib.misclib.Misc;
import com.seray.scaleviewlib.dialog.ScaleTipDialog;
import com.seray.scaleviewlib.utils.LogUtils;
import com.seray.scaleviewlib.utils.ToastUtils;
import com.tscale.scalelib.jniscale.JNIScale;

import java.lang.ref.WeakReference;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@ContentView(R.layout.fragment_correction_setting)
@ViewModel(CorrectionSettingViewModel.class)
public class CorrectionSettingFragment extends ASettingFragment<FragmentCorrectionSettingBinding, CorrectionSettingViewModel>
        implements View.OnTouchListener {
    private JNIScale mScale;
    private String[] arrDiv = {"1", "2", "5", "10", "20", "50", "100", "200", "500"};
    private String[] arrTrack;
    private String[] types = {"T-200", "SR-200"};
    private String[] rangeModes;
    private String[] zeroRangeTabs;
    protected Misc mMisc;
    private String[] mainUnit = {"设置主单位", "kg", "g"};


    private OperationHandler mOperationHandler = new OperationHandler(new WeakReference
            <>(this));
    private boolean isDefaultFdn = true;
    private boolean isDefaultBigFdn = true;
    private boolean isDefaultTrack = true;
    private boolean isDefaultType = true;
    private boolean isDefaultRangeMode = true;
    private boolean isDefaultZeroRange = true;
    private int step = 0;
    private int zeroStep = 0;
    private int zeroISN = 0;
    private float calload = 0.00f;

    private Runnable timerRun = new Runnable() {
        @Override
        public void run() {
            mOperationHandler.sendEmptyMessage(1);
        }
    };


    @Override
    public void saveData() {

    }

    /**
     * 防止点击穿透
     */
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // 拦截触摸事件，防止泄露下去
        view.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }


    private static class OperationHandler extends Handler {

        WeakReference<CorrectionSettingFragment> mWeakReference;

        OperationHandler(WeakReference<CorrectionSettingFragment> weakReference) {
            this.mWeakReference = weakReference;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            CorrectionSettingFragment activity = mWeakReference.get();
            if (activity != null) {
                if (msg.what == 1) {
                    activity._handleWeightChanged();
                }
            }
        }
    }

    /**
     * 执行定时任务固定数量线程池
     */
    private ScheduledExecutorService timerThreads = Executors.newScheduledThreadPool(1);

    private void _handleWeightChanged() {

        try {
            int count = mScale.getInternelCount();
            mBinding.internelCount.setText(String.valueOf(count));
            mBinding.weight.setText(mScale.getStringNet().trim());
        } catch (Exception e) {
            LogUtils.d("========" + e.toString());
            e.printStackTrace();
        }

//        System.out.println("----"+mScale.getStringNet().trim()+"--零点值--"+String.valueOf(count));
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initJNI();
        mMisc= Misc.newInstance();

    }

    private void initJNI() {
        mScale = JNIScale.getScale();
//        mScale.setMainUnit(0);
//        mScale.setUnit(1);
//        mScale.setFdnPtr(1);
//        mScale.setBigFdnPtr(1);
//        mScale.setStabDelay(150);//秤的稳定时间150  --> 0.75s
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View root = super.onCreateView(inflater, container, savedInstanceState);
        initData();
        initListener();
        timer();

        return root;

    }

    private void timer() {
        timerThreads.scheduleAtFixedRate(timerRun, 1500, 100, TimeUnit.MILLISECONDS);
    }

    @SuppressLint("SetTextI18n")
    private void initListener() {

        mBinding.setMainUnit.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
                .simple_spinner_dropdown_item, mainUnit));
        mBinding.showMainUnit.setText("当前单位为"+(mScale.getMainUnit()==0?"kg":"g"));
//        mBinding.settingSpFdn.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
//                .simple_spinner_dropdown_item, arrDiv));
//        mBinding.settingSpBigFdn.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
//                .simple_spinner_dropdown_item, arrDiv));
//        mBinding.settingSpZerotrack.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
//                .select_dialog_item, arrTrack));
//        mBinding.settingSpRangeMode.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
//                .select_dialog_item, rangeModes));
//        mBinding.settingSpZeroRange.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
//                .select_dialog_item, zeroRangeTabs));
//        mBinding.settingSpType.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
//                .select_dialog_item, types));

        mBinding.setMainUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultFdn) {
                    isDefaultFdn = false;
                    return;
                }
                if(position==0){

                }else if(position==1){
                    if(mScale.getMainUnit()==0){
                        return;
                    }
                    DialogSetUnit(0);
                }else if(position==2){
                    if(mScale.getMainUnit()==1){
                        return;
                    }
                    DialogSetUnit(1);
                }
//
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        mBinding.settingSpFdn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultFdn) {
                    isDefaultFdn = false;
                    return;
                }
//                boolean isOk =
//                mScale.setFdnPtr(position);
//                if (!isOk) {
//                    ToastUtils.showShort("分度值[1]设置失败");
//                } else {
//                    ToastUtils.showShort("分度值[1]设置成功");
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mBinding.settingSpBigFdn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultBigFdn) {
                    isDefaultBigFdn = false;
                    return;
                }
//                boolean isOk =
//                mScale.setBigFdnPtr(position);
//                if (!isOk) {
//                    ToastUtils.showShort("分度值[2]设置失败");
//                } else {
//                    ToastUtils.showShort("分度值[2]设置成功");
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mBinding.settingSpRangeMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultRangeMode) {
                    isDefaultRangeMode = false;
                    return;
                }
//                boolean isOk =
//                mScale.setRangeMode(position);
//                if (!isOk) {
//                    ToastUtils.showShort("量程模式设置失败");
//                } else {
//                    ToastUtils.showShort("量程模式设置设置成功");
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mBinding.settingSpZeroRange.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultZeroRange) {
                    isDefaultZeroRange = false;
                    return;
                }

//                mScale.setManualZeroRangePtr(position);

//                mScale.setAutoZeroRangePtr(position);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mBinding.settingSpZerotrack.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultTrack) {
                    isDefaultTrack = false;
                    return;
                }

//                mScale.setZeroTrackPtr(position);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mBinding.settingSpType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                if (isDefaultType) {
//                    isDefaultType = false;
//                    return;
//                }
//                if (position == 0) {
//                    AppConfig.SCALE_TYPE = AppConfig.ScaleType.T200;
//                    mBinding.settingSpFdn.setSelection(4);
//                    mBinding.settingSpRangeMode.setSelection(0);
//                    mBinding.etMaxuint.setText(R.string.max_weight_1);
//                } else if (position == 1) {
//                    AppConfig.SCALE_TYPE = AppConfig.ScaleType.SR200;
//                    mBinding.settingSpFdn.setSelection(1);
//                    mBinding.settingSpBigFdn.setSelection(2);
//                    mBinding.settingSpRangeMode.setSelection(1);
//                    mBinding.etMaxuint.setText(R.string.max_weight_2);
//                }
//                AppConfig.saveScaleTypeToDb();
//                showChangeScaleTypeDialog();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mBinding.calibration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 mMisc.beep();
                try {
                    if (step == 0) {

                        ((Button) (v)).setText(R.string.oper_calibrate_zero);
                        step++;
                    } else if (step == 1) {
                        if (mBinding.etCalload.getText().toString().isEmpty()) {
                            step = 0;
                            ((Button) (v)).setText(R.string.oper_calibrate);
                            return;
                        }
                        calload = Float.parseFloat(mBinding.etCalload.getText().toString().trim());
                        zeroISN = mScale.getInternelCount();
                        ((Button) (v)).setText(String.format("%s%skg", getString(R.string.oper_calibrate_weight), calload));
                        try{
                            if(mScale.getMainUnit()==1){
                                ((Button) (v)).setText(String.format("%s%sg", getString(R.string.oper_calibrate_weight), calload));
                            }else {
                                ((Button) (v)).setText(String.format("%s%skg", getString(R.string.oper_calibrate_weight), calload));
                            }
                        }catch (Exception e){
                            LogUtils.d(mScale.getMainUnit()+"=======");
                        }
                        step++;
                    } else if (step == 2) {
                        //第一个单位必须是kg
//                        if (mScale.getUnit()==1){
//                            DialogRestartApp("只能在kg模式下才可以标定，g模式下标定必须重启,重启后恢复默认kg模式");
//
//                        }else {
                            int count = mScale.getInternelCount();
                            boolean cali = mScale.saveNormalCalibration(zeroISN, count, calload);
                            if (cali) {
                                ToastUtils.showShort(R.string.oper_calibrate_success);
                            } else {
                                ToastUtils.showShort(R.string.oper_calibrate_failed);
                            }
                            ((Button) (v)).setText(R.string.oper_calibrate);
                            step = 0;
//                        }

                    }
                } catch (Exception e) {
                      LogUtils.d("saveNormalCalibration==="+e.toString());
                }
            }


        });

        mBinding.maxuint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMisc.beep();
                setManualUnit();
            }
        });

        mBinding.etZeroBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (zeroStep == 0) {
//                    mBinding.etZeroBtn.setText(R.string.oper_save_zero);
//                    int zeroCode = mScale.getInternelCount();
//                    mBinding.etZero.setText(String.valueOf(zeroCode));
//                    zeroStep++;
//                } else if (zeroStep == 1) {
//                    mBinding.etZeroBtn.setText(R.string.oper_reset);
//                    zeroStep = 0;
//                }
            }
        });

    }

    /**
     * 保存手动设置的最大量程
     */
    protected void setManualUnit() {
        String maxUnit = mBinding.etMaxuint.getText().toString();
        float inputMaxUnit;
        if (TextUtils.isEmpty(maxUnit)) {
            ToastUtils.showShort(R.string.oper_input_max_value);
        } else if (!NumFormatUtil.isNumeric(maxUnit)) {
            ToastUtils.showShort(R.string.oper_input_number);
            mBinding.etMaxuint.setText("");
        } else {
            inputMaxUnit = Float.parseFloat(maxUnit);// 输入的最大量程
//            if (inputMaxUnit > 300) {
//                ToastUtils.showShort(R.string.oper_over_max);
//            } else
            if (inputMaxUnit > 0) {
                mScale.setMainUnitFull(inputMaxUnit);// 设置主单位称重量程
                float midUnit = inputMaxUnit / 2;
                mScale.setMainUnitMidFull(midUnit);// 设置主单位半量程
                float curFullUnit = mScale.getMainUnitFull();
                if (curFullUnit == inputMaxUnit) {// 获取设置最大量程操作后的最大量程，可行
                    ToastUtils.showShort(R.string.oper_max_value_success);
                } else {
                    ToastUtils.showShort(R.string.oper_max_value_failed);
                }
            }
        }
    }


    private void showChangeScaleTypeDialog() {
        ScaleTipDialog tipDialog = new ScaleTipDialog(getActivity());
        tipDialog.show();
        tipDialog.setMessage(R.string.dialog_msg_demarcate);
        tipDialog.setOnPositiveClickListener(R.string.manage_submit, null);
    }

    public void initData() {
        arrTrack = getResources().getStringArray(R.array.division_values);
        rangeModes = getResources().getStringArray(R.array.range_mode);
        zeroRangeTabs = getResources().getStringArray(R.array.zero_mode);
        mBinding.settingSpFdn.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
                .simple_spinner_dropdown_item, arrDiv));
        mBinding.settingSpBigFdn.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
                .simple_spinner_dropdown_item, arrDiv));
        mBinding.settingSpZerotrack.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
                .select_dialog_item, arrTrack));
        mBinding.settingSpRangeMode.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
                .select_dialog_item, rangeModes));
        mBinding.settingSpZeroRange.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
                .select_dialog_item, zeroRangeTabs));
        mBinding.settingSpType.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout
                .select_dialog_item, types));

        // 获取当前秤的最大量程 默认是0.0f

        if (String.valueOf(mScale.getMainUnitFull()) != null && !TextUtils.isEmpty(String.valueOf(mScale.getMainUnitFull()))) {
            float curMainUnit = mScale.getMainUnitFull();
            String unitStr = String.valueOf(curMainUnit);
            if (curMainUnit == 0.0f) {
                curMainUnit = AppConfig.isT200() ? 300.0f : 30.0f;
            }
            mBinding.etMaxuint.setText(unitStr);
        }
    }

    @Override
    public void onStop() {
        mOperationHandler.removeCallbacksAndMessages(null);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private long lastClickTime;

    public boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }


    @Override
    public String getFragmentTitle() {
        return Utils.getApp().getString(R.string.setting_frag_name_correction);
    }


    public void DialogSetUnit(int position) {
        String showMainUnit = "";
        if(position==0){
            showMainUnit="kg";
        }else if(position==1){
            showMainUnit="g";
        }
        AlertDialog normalDialog =
                new AlertDialog.Builder(getActivity())
                        .setTitle("修改主单位,修改后必须重新校正")
                        .setMessage("主单位修改为"+showMainUnit +"及显示单位跟着修改")
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @SuppressLint("SetTextI18n")
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        try {
                                             mScale.setMainUnit(position);
                                             mScale.setUnit(position);
                                             mBinding.showMainUnit.setText("当前单位为"+(mScale.getMainUnit()==0?"kg":"g"));
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }

                                    }
                                }).
                        create();
        normalDialog.show();

    }
    public void DialogRestartApp(String showErr) {
        AlertDialog normalDialog =
                new AlertDialog.Builder(getActivity())
                        .setTitle("重启App:")
                        .setMessage(showErr)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        try {
                                            int count = mScale.getInternelCount();
                                            boolean cali = mScale.saveNormalCalibration(zeroISN, count, calload);
                                            if (cali) {
                                                ToastUtils.showShort(R.string.oper_calibrate_success);
                                            } else {
                                                ToastUtils.showShort(R.string.oper_calibrate_failed);
                                            }
                                            mBinding.calibration.setText(R.string.oper_calibrate);
                                            step = 0;

                                            restartApp(getActivity());
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }

                                    }
                                }).create();
        normalDialog.setCanceledOnTouchOutside(false);
        normalDialog.setCancelable(false);
        normalDialog.show();

    }

    /**
     * 重启app
     * @param context
     */
    public static void restartApp(Context context) {

        final Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.kedacom.freedomLabel");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
        System.exit(0);

//        Intent intent =context.getPackageManager()
//                .getLaunchIntentForPackage(context.getPackageName());
//        PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
//        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
//        System.exit(0);
    }
}